var electionRecordId = "";
var setting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyorgget/getPartyOrgTree",// Ajax 获取数据的 URL 地址
        autoParam: ["partyOrgId"],// 异步加载时需要自动提交父节点属性的参数
    },
    callback: {
        onClick: zTreeOnClick
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "partyOrgId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "partyOrgName"
        }
    }
};
$(function () {
    var topNode = [{
        partyOrgName: orgName,
        levelId: '',
        isParent: "true",
        partyOrgId: "0",
        icon: "/gobal/img/org/org.png"
    }];
    zTree = $.fn.zTree.init($("#tree"), setting, topNode);// 初始化树节点时，添加同步获取的数据
    var nodes = zTree.getNodes();
    for (var i = 0; i < nodes.length; i++) {
        zTree.expandNode(nodes[i], true, false, false);// 默认展开第一级节点
    }
    jeDate("#electionTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#workBeginTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#workEndTime", {
        format: "YYYY-MM-DD"
    });
    $("#createbut").unbind("click").click(function () {
        layer.msg("请选择党组织！");
    })

    $.ajax({
        url: "/ret/partyparamget/getGovPostTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            zTree = $.fn.zTree.init($("#govPosttree"), setting, data);// 初始化树节点时，添加同步获取的数据
            var topNode = [{
                sortName: "请选择",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#govPostTree"), govPostsetting, newTreeNodes);
        }
    });
    $("#govPost").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#govPostContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $(".menuContent").hide();
    });
    $(".menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
})

function zTreeOnClick(event, treeId, treeNode) {
    document.getElementById("form1").reset();
    $("#partyOrgId").attr("data-value", "");
    if (treeNode.partyOrgId == "0") {
        layer.msg("请选择具体党组织！");
    } else {
        $("#partyOrgId").attr("data-value", treeNode.partyOrgId);
        $.ajax({
            url: "/ret/partyorgget/getPartyOrgById",
            type: "post",
            dataType: "json",
            data: {
                partyOrgId: treeNode.partyOrgId
            },
            success: function (data) {
                if (data.status == 200) {
                    var v = data.list;
                    for (name in v) {
                        if (name == "partyOrgName") {
                            $("#partyOrgId").val(v.partyOrgName);
                        }
                    }

                } else if (data.status == 100) {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
                getElectionStatus(treeNode.partyOrgId);
            }
        });
        $(".js-btn").unbind("click").click(function () {
            $("#wydiv").modal("show");
            $(".js-save").unbind("click").click(function () {
                addCommittee();
            })
        })
    }
}

function getElectionStatus(partyOrgId) {
    $.ajax({
        url: "/ret/partyorgget/electionIsExist",
        type: "post",
        dataType: "json",
        data: {
            partyOrgId: partyOrgId
        },
        success: function (data) {
            if (data.status == "200") {
                if (data.list == undefined) {
                    $("#updatabut").hide();
                    $("#delbut").hide();
                    $("#createbut").show();
                    $("#createbut").unbind("click").click(function () {
                        addElection();
                    })
                    $('#myTable').bootstrapTable('destroy');
                } else {
                    $.ajax({
                        url: "/ret/partyorgget/getPartyElectionById",
                        type: "post",
                        dataType: "json",
                        data: {
                            rercordId: data.list.rercordId
                        },
                        success: function (res) {
                            if (res.status == "200") {
                                for (var id in res.list) {
                                    if (id == "recordId") {
                                        electionRecordId = res.list[id];
                                        $("#updatabut").unbind("click").click(function () {
                                            updateElection(electionRecordId)
                                        })
                                        $("#delbut").unbind("click").click(function () {
                                            deleteElection(electionRecordId)
                                        })
                                    } else if (id == "partyOrgId") {

                                    } else if (id == "recordId") {

                                    } else {
                                        $("#" + id).val(res.list[id]);
                                    }
                                }
                                query();
                            } else if (data.status == "100") {
                                layer.msg(rs.msg);
                            } else {
                                console.log(res.msg);
                            }

                        }
                    });
                    $("#createbut").hide();
                    $("#updatabut").show();
                    $("#delbut").show();
                }
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}


function addCommittee() {
    if (electionRecordId == "") {
        layer.msg("选举届期不正确");
    } else {
        $.ajax({
            url: "/set/partyorgset/insertPartyCommittee",
            type: "post",
            dataType: "json",
            data: {
                electionRecordId: electionRecordId,
                partyOrgId: $("#partyOrgId").attr("data-value"),
                sortNo: $("#sortNo").val(),
                partyMember: $("#partyMember").attr("data-value"),
                workFlag: $("#workFlag").val(),
                takeType: $("#takeType").val(),
                govPost: $("#govPost").attr("data-value"),
                workBeginTime: $("#workBeginTime").val(),
                workEndTime: $("#workEndTime").val()
            },
            success: function (data) {
                console.log(data);
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $('#myTable').bootstrapTable('refresh');
                    $("#wydiv").modal("hide");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}

function editcommittee(recordId) {
    document.getElementById("form2").reset();
    $("#partyMember").attr("data-value", "");
    $("#govPost").attr("data-value", "");
    $("#wydiv").modal("show");
    $.ajax({
        url: "/ret/partyorgget/getPartyCommitteeById",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId
        },
        success: function (data) {
            if (data.status == "200") {
                var info = data.list;
                for (var id in info) {
                    if (id == "partyMember") {
                        $("#" + id).attr("data-value", info[id]);
                        $.ajax({
                            url: "/ret/partymemberget/getPartyMemberById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                memberId: info[id]
                            },
                            success: function (res) {
                                if (res.status = "200") {
                                    $("#partyMember").val(res.list.userName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else {
                                    console.log(res.msg);
                                }
                            }
                        });
                    } else if (id == "govPost") {
                        $("#" + id).attr("data-value", info[id]);
                        $.ajax({
                            url: "/ret/partyparamget/getGovPostById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: info[id]
                            },
                            success: function (res) {
                                if (res.status = "200") {
                                    $("#govPost").val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else {
                                    console.log(res.msg);
                                }
                            }
                        });
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $(".js-save").unbind("click").click(function () {
                    updateCommittee(recordId);
                })

            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });

}


function updateCommittee(recordId) {
    if (electionRecordId == "") {
        layer.msg("选举届期不正确");
    } else {
        $.ajax({
            url: "/set/partyorgset/updatePartyCommittee",
            type: "post",
            dataType: "json",
            data: {
                recordId: recordId,
                electionRecordId: electionRecordId,
                partyOrgId: $("#partyOrgId").attr("data-value"),
                sortNo: $("#sortNo").val(),
                partyMember: $("#partyMember").attr("data-value"),
                workFlag: $("#workFlag").val(),
                takeType: $("#takeType").val(),
                govPost: $("#govPost").attr("data-value"),
                workBeginTime: $("#workBeginTime").val(),
                workEndTime: $("#workEndTime").val()
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $('#myTable').bootstrapTable('refresh');
                    $("#wydiv").modal("hide");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}


function addElection() {

    if ($("#partyOrgId").attr("data-value") == "") {
        layer.msg("党组织不能为空！");
    } else {
        $.ajax({
            url: "/set/partyorgset/insertPartyElection",
            type: "post",
            dataType: "json",
            data: {
                partyOrgId: $("#partyOrgId").attr("data-value"),
                election: $("#election").val(),
                electionTime: $("#electionTime").val(),
                createType: $("#createType").val(),
                endTime: $("#endTime").val(),
                due: $("#due").val(),
                actual: $("#actual").val()
            },
            success: function (data) {
                console.log(data);
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}


function deleteElection(recordId) {
    $.ajax({
        url: "/set/partyorgset/deletePartyElection",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}


function updateElection(recordId) {
    $.ajax({
        url: "/set/partyorgset/updatePartyElection",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            partyOrgId: $("#partyOrgId").attr("data-value"),
            election: $("#election").val(),
            electionTime: $("#electionTime").val(),
            createType: $("#createType").val(),
            endTime: $("#endTime").val(),
            due: $("#due").val(),
            actual: $("#actual").val()
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}


function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/partyorgget/getCommitteeList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        sortOrder: "desc",
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'recordId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: '序号',//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'partyOrgName',
                title: '所在支部',
                width: '100px'
            },
            {
                field: 'userName',
                title: '姓名',
                width: '100px'
            },

            {
                field: 'workFlag',
                width: '50px',
                title: '兼职标识',
                formatter: function (value, row, index) {
                    if (value == "1") {
                        return "兼职";
                    } else if (value == "2") {
                        return "专职";
                    } else {
                        return "未知";
                    }
                }
            },
            {
                field: 'takeType',
                title: '任职方式',
                width: '100px',
                visible: false,
                formatter: function (value, row, index) {
                    if (value == "1") {
                        return "党委决定任职";
                    } else if (value == "2") {
                        return "差额选举";
                    } else if (value == "3") {
                        return "等额选举";
                    } else {
                        return "未知";
                    }

                }
            },
            {
                field: 'govPost',
                width: '100px',
                visible: false,
                title: '职务名称'
            },
            {
                field: 'workBeginTime',
                width: '100px',
                title: '任职起始日期'
            },
            {
                field: 'workEndTime',
                width: '100px',
                title: '任职结束日期'
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                width: '150px',
                formatter: function (value, row, index) {
                    return createOptBtn(row.recordId);
                }
            }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        electionRecordId: electionRecordId
    };
    return temp;
};

function createOptBtn(recordId) {
    var html = "<a href=\"javascript:void(0);editcommittee('" + recordId + "')\" class=\"btn btn-success btn-xs\" >编辑</a>&nbsp;&nbsp;" +
        "<a href=\"javascript:void(0);delcommittee('" + recordId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function delcommittee(recordId) {
    $.ajax({
        url: "/set/partyorgset/deletePartyCommittee",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                $('#myTable').bootstrapTable('refresh');
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}

var govPostsetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getGovPostTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("govPostTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#govPost");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};
